# -*- coding: utf-8 -*-
"""
乒乓球培训管理系统 - 仪表板视图

仪表板蓝图，为不同角色提供专属的仪表板页面
包括超级管理员、校区管理员、教练、学员四种角色的仪表板
"""

from flask import Blueprint, render_template, redirect, url_for, jsonify, current_app
from flask_login import login_required, current_user
from sqlalchemy import func, and_, or_
from datetime import datetime, timedelta
from app import db
from app.models.user import User
from app.models.campus import Campus
from app.models.relation import StudentCoachRelation
from app.models.reservation import Reservation
from app.models.account import UserAccount, Transaction
from app.models.table import Table
from app.models.evaluation import Evaluation
from app.utils.decorators import (
    super_admin_required,
    campus_admin_required,
    coach_required,
    student_required,
    api_auth_required
)

# 创建仪表板蓝图
dashboard_bp = Blueprint('dashboard', __name__)


@dashboard_bp.route('/')
@dashboard_bp.route('/index')
@login_required
def index():
    """
    系统首页重定向处理

    根据用户角色重定向到对应的仪表板：
    - 超级管理员：全系统统计仪表板
    - 校区管理员：校区管理仪表板
    - 教练：教练个人仪表板
    - 学员：学员个人仪表板

    Returns:
        redirect: 重定向响应对象
    """
    if current_user.is_super_admin():
        return redirect(url_for('dashboard.super_admin'))
    elif current_user.is_campus_admin():
        return redirect(url_for('dashboard.campus_admin'))
    elif current_user.is_coach():
        return redirect(url_for('dashboard.coach'))
    elif current_user.is_student():
        return redirect(url_for('dashboard.student'))
    else:
        # 如果角色不明确，重定向到登录页
        return redirect(url_for('auth.login'))


@dashboard_bp.route('/super-admin')
@super_admin_required
def super_admin():
    """
    超级管理员仪表板

    显示全系统的统计数据和管理概览
    """
    try:
        # 基础统计数据
        stats = {
            'total_campuses': Campus.query.count(),
            'total_users': User.query.filter(User.status != 'inactive').count(),
            'total_students': User.query.filter(and_(User.role == 'student', User.status == 'active')).count(),
            'total_coaches': User.query.filter(and_(User.role == 'coach', User.status == 'active')).count(),
            'pending_coaches': User.query.filter(and_(User.role == 'coach', User.status == 'pending')).count(),
            'total_relations': StudentCoachRelation.query.filter_by(status='approved').count(),
        }

        # 今日数据
        today = datetime.now().date()
        today_start = datetime.combine(today, datetime.min.time())
        today_end = datetime.combine(today, datetime.max.time())
        today_stats = {
            'new_students': User.query.filter(
                and_(
                    User.role == 'student',
                    User.created_at >= today_start,
                    User.created_at <= today_end
                )
            ).count(),
            'new_coaches': User.query.filter(
                and_(
                    User.role == 'coach',
                    User.created_at >= today_start,
                    User.created_at <= today_end
                )
            ).count(),
            'today_reservations': Reservation.query.filter(
                Reservation.reservation_date == today
            ).count(),
        }

        # 校区列表及其统计
        campuses = []
        for campus in Campus.query.filter_by(status='active').all():
            campus_stats = {
                'campus': campus,
                'students_count': User.query.filter(
                    and_(User.campus_id == campus.id, User.role == 'student', User.status == 'active')
                ).count(),
                'coaches_count': User.query.filter(
                    and_(User.campus_id == campus.id, User.role == 'coach', User.status == 'active')
                ).count(),
                'tables_count': Table.query.filter_by(campus_id=campus.id, status='available').count(),
            }
            campuses.append(campus_stats)

        # 最近注册的用户
        recent_users = User.query.filter(User.status != 'inactive').order_by(
            User.created_at.desc()
        ).limit(10).all()

        return render_template(
            'dashboard/super_admin.html',
            stats=stats,
            today_stats=today_stats,
            campuses=campuses,
            recent_users=recent_users
        )

    except Exception as e:
        # 记录错误日志
        print(f"Super admin dashboard error: {str(e)}")
        return render_template('dashboard/super_admin.html', stats={}, error="数据加载失败")


@dashboard_bp.route('/campus-admin')
@campus_admin_required
def campus_admin():
    """
    校区管理员仪表板

    显示本校区的管理数据和统计信息
    """
    try:
        campus_id = current_user.campus_id

        # 基础统计数据
        stats = {
            'total_students': User.query.filter(
                and_(User.campus_id == campus_id, User.role == 'student', User.status == 'active')
            ).count(),
            'total_coaches': User.query.filter(
                and_(User.campus_id == campus_id, User.role == 'coach', User.status == 'active')
            ).count(),
            'pending_coaches': User.query.filter(
                and_(User.campus_id == campus_id, User.role == 'coach', User.status == 'pending')
            ).count(),
            'total_tables': Table.query.filter_by(campus_id=campus_id, status='available').count(),
            'total_relations': StudentCoachRelation.query.join(User, StudentCoachRelation.student_id == User.id).filter(
                and_(User.campus_id == campus_id, StudentCoachRelation.status == 'approved')
            ).count(),
        }

        # 今日数据
        today = datetime.now().date()
        today_stats = {
            'new_students': User.query.filter(
                and_(User.campus_id == campus_id, User.role == 'student', func.date(User.created_at) == today)
            ).count(),
            'today_reservations': Reservation.query.join(Table).filter(
                and_(Table.campus_id == campus_id, Reservation.reservation_date == today)
            ).count(),
        }

        # 待审核的教练申请
        pending_coaches = User.query.filter(
            and_(User.campus_id == campus_id, User.role == 'coach', User.status == 'pending')
        ).order_by(User.created_at.desc()).limit(10).all()

        # 最近的师生关系申请
        recent_relations = StudentCoachRelation.query.join(
            User, StudentCoachRelation.student_id == User.id
        ).filter(
            and_(User.campus_id == campus_id, StudentCoachRelation.status == 'pending')
        ).order_by(StudentCoachRelation.applied_at.desc()).limit(10).all()

        # 校区信息
        campus = Campus.query.get(campus_id)

        return render_template(
            'dashboard/campus_admin.html',
            stats=stats,
            today_stats=today_stats,
            pending_coaches=pending_coaches,
            recent_relations=recent_relations,
            campus=campus
        )

    except Exception as e:
        print(f"Campus admin dashboard error: {str(e)}")
        return render_template('dashboard/campus_admin.html', stats={}, error="数据加载失败")


@dashboard_bp.route('/coach')
@coach_required
def coach():
    """
    教练仪表板

    显示教练的学员、课程安排和收入统计
    """
    try:
        coach_id = current_user.id
        print(f"Coach ID: {coach_id}")

        # 基础统计数据 - 逐步测试
        try:
            total_students = StudentCoachRelation.query.filter_by(
                coach_id=coach_id,
                status='approved'
            ).count()
            print(f"Total students: {total_students}")
        except Exception as e:
            print(f"Error getting total students: {e}")
            total_students = 0

        try:
            pending_requests_count = StudentCoachRelation.query.filter_by(
                coach_id=coach_id,
                status='pending'
            ).count()
            print(f"Pending requests: {pending_requests_count}")
        except Exception as e:
            print(f"Error getting pending requests: {e}")
            pending_requests_count = 0

        stats = {
            'total_students': total_students,
            'pending_requests': pending_requests_count,
        }

        # 今日课程
        try:
            today = datetime.now().date()
            print(f"Today: {today}")

            today_reservations = Reservation.query.filter_by(
                coach_id=coach_id,
                reservation_date=today
            ).filter(
                Reservation.status.in_(['confirmed', 'in_progress'])
            ).order_by(Reservation.start_time).all()
            print(f"Today reservations count: {len(today_reservations)}")
        except Exception as e:
            print(f"Error getting today reservations: {e}")
            today_reservations = []

        # 本周课程统计
        try:
            week_start = today - timedelta(days=today.weekday())
            week_end = week_start + timedelta(days=6)
            print(f"Week range: {week_start} to {week_end}")

            week_lessons = Reservation.query.filter_by(
                coach_id=coach_id,
                status='completed'
            ).filter(
                Reservation.reservation_date >= week_start,
                Reservation.reservation_date <= week_end
            ).count()
            print(f"Week lessons: {week_lessons}")
        except Exception as e:
            print(f"Error getting week stats: {e}")
            week_lessons = 0

        week_stats = {
            'total_lessons': week_lessons,
        }

        # 本月收入统计（暂时设为0）
        monthly_income = 0

        # 我的学员 - 使用更简单的查询方式
        try:
            # 先获取关系记录
            approved_relations = StudentCoachRelation.query.filter_by(
                coach_id=coach_id,
                status='approved'
            ).limit(10).all()
            print(f"Approved relations count: {len(approved_relations)}")

            # 然后获取对应的学员信息
            my_students = []
            for relation in approved_relations:
                student = User.query.get(relation.student_id)
                if student:
                    my_students.append((student, relation))
            print(f"My students count: {len(my_students)}")
        except Exception as e:
            print(f"Error getting my students: {e}")
            my_students = []

        # 待处理的学员申请
        try:
            # 先获取待处理的关系记录
            pending_relation_records = StudentCoachRelation.query.filter_by(
                coach_id=coach_id,
                status='pending'
            ).order_by(StudentCoachRelation.applied_at.desc()).all()
            print(f"Pending relations count: {len(pending_relation_records)}")

            # 然后获取对应的学员信息
            pending_requests = []
            for relation in pending_relation_records:
                student = User.query.get(relation.student_id)
                if student:
                    pending_requests.append((student, relation))
            print(f"Pending requests with students: {len(pending_requests)}")
        except Exception as e:
            print(f"Error getting pending requests: {e}")
            pending_requests = []

        return render_template(
            'dashboard/coach.html',
            stats=stats,
            week_stats=week_stats,
            monthly_income=monthly_income,
            today_reservations=today_reservations,
            my_students=my_students,
            pending_requests=pending_requests
        )

    except Exception as e:
        import traceback
        error_details = traceback.format_exc()
        print(f"Coach dashboard error: {str(e)}")
        print(f"Full traceback: {error_details}")
        current_app.logger.error(f"Coach dashboard error: {str(e)}")
        current_app.logger.error(f"Full traceback: {error_details}")
        return render_template('dashboard/coach.html', stats={}, error=f"数据加载失败: {str(e)}")


@dashboard_bp.route('/student')
@student_required
def student():
    """
    学员仪表板

    显示学员的教练、课程安排和学习进度
    """
    try:
        student_id = current_user.id

        # 基础统计数据
        stats = {
            'total_coaches': StudentCoachRelation.query.filter(
                and_(StudentCoachRelation.student_id == student_id, StudentCoachRelation.status == 'approved')
            ).count(),
            'pending_applications': StudentCoachRelation.query.filter(
                and_(StudentCoachRelation.student_id == student_id, StudentCoachRelation.status == 'pending')
            ).count(),
        }

        # 账户余额
        account = UserAccount.query.filter_by(user_id=student_id).first()
        account_balance = account.balance if account else 0

        # 今日课程
        today = datetime.now().date()
        today_reservations = Reservation.query.filter(
            and_(
                Reservation.student_id == student_id,
                Reservation.reservation_date == today,
                Reservation.status.in_(['confirmed', 'in_progress'])
            )
        ).order_by(Reservation.start_time).all()

        # 本周课程统计
        week_start = today - timedelta(days=today.weekday())
        week_end = week_start + timedelta(days=6)

        week_stats = {
            'total_lessons': Reservation.query.filter(
                and_(
                    Reservation.student_id == student_id,
                    Reservation.reservation_date >= week_start,
                    Reservation.reservation_date <= week_end,
                    Reservation.status == 'completed'
                )
            ).count(),
        }

        # 我的教练
        my_coaches = db.session.query(User, StudentCoachRelation).join(
            StudentCoachRelation, User.id == StudentCoachRelation.coach_id
        ).filter(
            and_(StudentCoachRelation.student_id == student_id, StudentCoachRelation.status == 'approved')
        ).all()

        # 最近的课程评价
        recent_evaluations = Evaluation.query.filter_by(student_id=student_id).order_by(
            Evaluation.created_at.desc()
        ).limit(5).all()

        # 最近的消费记录
        recent_transactions = Transaction.query.filter_by(user_id=student_id).order_by(
            Transaction.created_at.desc()
        ).limit(10).all()

        return render_template(
            'dashboard/student.html',
            stats=stats,
            week_stats=week_stats,
            account_balance=account_balance,
            today_reservations=today_reservations,
            my_coaches=my_coaches,
            recent_evaluations=recent_evaluations,
            recent_transactions=recent_transactions
        )

    except Exception as e:
        import traceback
        error_details = traceback.format_exc()
        print(f"Student dashboard error: {str(e)}")
        print(f"Full traceback: {error_details}")
        current_app.logger.error(f"Student dashboard error for user {current_user.id}: {str(e)}")
        current_app.logger.error(f"Full traceback: {error_details}")
        return render_template('dashboard/student.html', stats={}, error=f"数据加载失败")


@dashboard_bp.route('/api/stats')
@api_auth_required
def api_stats():
    """
    API接口：获取仪表板统计数据

    根据用户角色返回相应的统计数据（用于AJAX更新）
    """
    try:
        if current_user.is_super_admin():
            stats = {
                'total_users': User.query.filter(User.status != 'inactive').count(),
                'total_campuses': Campus.query.filter_by(status='active').count(),
                'pending_coaches': User.query.filter(
                    and_(User.role == 'coach', User.status == 'pending')
                ).count(),
            }
        elif current_user.is_campus_admin():
            campus_id = current_user.campus_id
            stats = {
                'total_students': User.query.filter(
                    and_(User.campus_id == campus_id, User.role == 'student', User.status == 'active')
                ).count(),
                'pending_coaches': User.query.filter(
                    and_(User.campus_id == campus_id, User.role == 'coach', User.status == 'pending')
                ).count(),
            }
        elif current_user.is_coach():
            coach_id = current_user.id
            stats = {
                'total_students': StudentCoachRelation.query.filter(
                    and_(StudentCoachRelation.coach_id == coach_id, StudentCoachRelation.status == 'approved')
                ).count(),
                'pending_requests': StudentCoachRelation.query.filter(
                    and_(StudentCoachRelation.coach_id == coach_id, StudentCoachRelation.status == 'pending')
                ).count(),
            }
        elif current_user.is_student():
            student_id = current_user.id
            account = UserAccount.query.filter_by(user_id=student_id).first()
            stats = {
                'account_balance': float(account.balance) if account else 0.0,
                'total_coaches': StudentCoachRelation.query.filter(
                    and_(StudentCoachRelation.student_id == student_id, StudentCoachRelation.status == 'approved')
                ).count(),
            }
        else:
            stats = {}

        return jsonify({'success': True, 'stats': stats})

    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500
